/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servidor;

import Entidades.Curso;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author imarban
 */
class ServerCurso extends Thread{
    
    String driver = "com.mysql.jdbc.Driver";
    String usuario = "root";
    String clave = "root";
    String urlDB = "jdbc:mysql://localhost/Escuela";
    
    private Socket socketCliente = null;
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    int codigoOperacion;
    
    Connection cnn;
    PreparedStatement pst;
    ResultSet rs;
    ResultSetMetaData rsMetaData;
    
     public ServerCurso(Socket socketCliente, ObjectInputStream ois, ObjectOutputStream oos){
        this.socketCliente = socketCliente;
        System.out.println("Inicialice el serverAlumno");
        try {
            this.oos = oos;
            this.ois = ois;            
            } catch (Exception ioe) {
            System.out.println(ioe.getMessage());
            throw new RuntimeException();
        }start();
    }

    @Override
    public void run() {
        try {
            codigoOperacion = ois.readInt();
            System.out.println("Lei un codigo de " + codigoOperacion);
            switch(codigoOperacion)
            {
                case Constantes.AGREGAR:
                    agregarCurso();
                    break;
                case Constantes.MODIFICAR:
                    modificarCurso();
                    break;
                case Constantes.ELIMINAR: 
                    eliminarCurso();
                    break;
                case Constantes.CONSULTAR_UNO: 
                    enviarCurso();
                    break;
                case Constantes.CONSULTAR_TODOS: 
                    enviarListaCursos();
                    break;
            }
        } catch (IOException e) {
        }
        
           
    } 

    private void enviarCurso()
    {
        int idCurso;
        Curso curso;
        conectarBD();
        
        try{
            idCurso = ois.readInt();
            pst = cnn.prepareStatement("SELECT * FROM Curso WHERE idCurso = ?");
            pst.setInt(1, idCurso);
            rs = pst.executeQuery();
            rs.first();
            curso = new Curso(rs.getInt(1), rs.getString(2), rs.getString(3), 
                        rs.getString(4), rs.getFloat(5));
            
            oos.writeObject(curso);
            oos.flush();
        } catch (IOException | SQLException  e){
            
        }
    }
    
    private void enviarListaCursos() {
        List<Curso> cursos = new ArrayList<Curso>();
        conectarBD();
        try {
            pst = cnn.prepareStatement("SELECT * FROM Curso");
            rs = pst.executeQuery();            
            while(rs.next())
            {
                cursos.add(new Curso(rs.getInt(1), rs.getString(2), rs.getString(3), 
                        rs.getString(4), rs.getFloat(5)));
            }
            oos.writeObject(cursos);
            oos.flush();
        } catch (SQLException | IOException e) {
        }       
    }

    private void agregarCurso() {
        
       conectarBD();
        try {
            pst = cnn.prepareStatement("INSERT INTO Curso VALUES (null,?,?,?,?)");    
        } catch (SQLException sqle) {
        }
  
        try {
            Curso curso = (Curso)ois.readObject();
            
            pst.setString(1, curso.getNombre());
            pst.setString(2, curso.getFechaI());
            pst.setString(3, curso.getFechaT());
            pst.setFloat(4, curso.getCuota());
            
            pst.executeUpdate();
            oos.writeBoolean(true);
        } catch (ClassNotFoundException | IOException  | SQLException cnfe) {
            try {
                oos.writeBoolean(false);
            } catch (IOException e) {
            }
            System.err.println(cnfe.getMessage());
            throw new RuntimeException();
        } finally{
            try {
                oos.flush();
            } catch (Exception e) {
            }
        }
        
    }
    
    private void modificarCurso()
    {
        Curso curso;
        conectarBD();
        try {
            curso = (Curso) ois.readObject();
            pst = cnn.prepareStatement("UPDATE Curso SET nombre =  ?, fechaInicio = ?, fechaFin = ?, cuotaDeRecuperacion = ? WHERE idCurso = ?");
            
            pst.setString(1, curso.getNombre());
            pst.setString(2, curso.getFechaI());
            pst.setString(3, curso.getFechaT());
            pst.setFloat(4, curso.getCuota());
            pst.setInt(5, curso.getId());
            
            pst.executeUpdate();
            
            oos.writeBoolean(true);
            oos.flush();
        } catch (IOException | ClassNotFoundException | SQLException ioe) {
            try {
                oos.writeBoolean(false);
                oos.flush();
            } catch (Exception e) {
            }
            System.err.println(ioe.getMessage());
            throw new RuntimeException();
        }

    }
    
    private void eliminarCurso(){
       int idCurso;
        conectarBD();
        try {
            idCurso = ois.readInt();    
            System.out.println("Recibi el identificador del curso " + idCurso);
            pst = cnn.prepareStatement("DELETE FROM Curso WHERE idCurso = ?");
            pst.setInt(1, idCurso);
            pst.executeUpdate();
            oos.writeBoolean(true);
            oos.flush();
        } catch (IOException | SQLException ioe) {
            try {
                oos.writeBoolean(false);
                oos.flush();
            } catch (Exception e) {
            }
            System.err.println(ioe.getMessage());
            throw new RuntimeException();
        }
    }
        
    private void conectarBD()
    {
         try {
            Class.forName(driver);
            cnn = DriverManager.getConnection(urlDB, usuario, clave);
         } catch (SQLException | ClassNotFoundException sqle){
             System.err.println(sqle.getMessage());
         }
    }
    
    
        
}
